<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\WorkMessage\Action\Dashboard;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\User\Logic\Traits\UserTrait;
use MoChat\App\WorkContact\Contract\WorkContactContract;
use MoChat\App\WorkEmployee\Contract\WorkEmployeeContract;
use MoChat\App\WorkMessage\Constants\MsgType;
use MoChat\App\WorkMessage\Contract\WorkMessageContract;
use MoChat\App\WorkMessage\Contract\WorkMessageIndexContract;
use MoChat\App\WorkRoom\Contract\WorkRoomContract;
use MoChat\Framework\Action\AbstractAction;

/**
 * @Controller
 */
class RoomMessage extends AbstractAction
{
    use UserTrait;

    /**
     * @var WorkMessageContract
     */
    protected $workMessageService;

    /**
     * @Inject
     * @var WorkEmployeeContract
     */
    protected $workEmployeeService;

    /**
     * @Inject
     * @var WorkContactContract
     */
    protected $workContactService;

    /**
     * @Inject
     * @var WorkRoomContract
     */
    protected $workRoomClient;

    /**
     * @Inject
     * @var WorkMessageIndexContract
     */
    protected $workMsgIndexService;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/workMessage/roomMessage", methods="GET")
     */
    public function handle(): array
    {
        // 请求参数.验证
        $corpId = $this->corpId();
        $this->workMessageService = make(WorkMessageContract::class, [$corpId]);

        $where = [
            ['corp_id', '=', $corpId],
        ];
        if (! empty($this->request->query('roomName'))) {
            $where[] = ['name', 'like', '%' . $this->request->query('roomName') . '%'];
        }

        $toData = $this->getToList($where);

        $data = [];
        foreach ($toData['data'] as $k => $v) {
            $lastMsg = $this->workMessageService->getWorkMessagesLastByWxRoomId($v['wxChatId'], ['id', 'msg_time', 'content', 'msg_type', 'wx_room_id']);

            $data[$k] = [
                'name' => $v['name'],
                'avatar' => '',
                'lastMsgTime' => '',
                'content' => '',
                'wxRoomId' => $v['wxChatId'],
            ];

            if (! empty($lastMsg[0])) {
                $day = date('n-j', (int) ($lastMsg[0]->msg_time * 0.001));
                $dayArr = explode('-', $day);
                $msgDataTime = $dayArr[0] . '月' . $dayArr[1] . '日';

                $data[$k]['lastMsgTime'] = $msgDataTime;
                $data[$k]['content'] = $this->typeContent((int) $lastMsg[0]->msg_type, $lastMsg[0]->content);
            }
        }
        return [
            'page' => [
                'perPage' => $toData['per_page'],
                'total' => $toData['total'],
                'totalPage' => $toData['last_page'],
            ],
            'list' => $data,
        ];
    }

    /**
     * 聊天对象 - 列表数据.
     * @param array $where ...
     * @return array ...
     */
    protected function getToList(array $where): array
    {
        $options = [
            'page' => $this->request->query('page', 1),
            'perPage' => $this->request->query('perPage', 10),
        ];

        return $this->workRoomClient->getWorkRoomList($where, ['*'], $options);
    }

    /**
     * 获取类型消息.
     * @param int $type ...
     * @param null|string $content ...json
     * @return string ...
     */
    protected function typeContent(int $type, ?string $content): string
    {
        if (empty($content)) {
            return '';
        }
        $contentArr = json_decode($content, true);
        if (empty($contentArr)) {
            return '';
        }
        if ($type === MsgType::TEXT) {
            return $contentArr['content'];
        }
        if (in_array($type, MsgType::$fixedType, true)) {
            return MsgType::getMessage($type);
        }
        return '其它类型消息';
    }
}
